package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.properties.ShopProperties;
import com.sky.properties.WeChatProperties;
import com.sky.result.PageResult;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private ShopProperties shopProperties;

    /**
     * 用户下单
     * @param dto
     * @return
     */
    @Transactional   //0. 开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        //获取当前登录人id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        //根据地址簿id查询地址信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        String address =addressBook.getProvinceName()+addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        if (!this.checkOutOfRange(address)){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_OUT_RANGE);
        };


        //根据用户id查询购物车数据
        List<ShoppingCart> cartList = shoppingCartMapper.getByUserId(userId);
        if (cartList == null || cartList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1. 构造订单数据对象orders，将orders插入到orders表中
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);

        //1.1 需要补充属性字段
        orders.setNumber(System.currentTimeMillis()+"");    //订单号
        orders.setStatus(Orders.PENDING_PAYMENT);           //订单状态：1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setUserId(userId);                           //用户id
        orders.setOrderTime(LocalDateTime.now());           //下单时间
        orders.setPayStatus(Orders.UN_PAID);                //支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());            //联系人手机号
        orders.setAddress(addressBook.getDetail());         //收货地址
        orders.setConsignee(addressBook.getConsignee());    //收货人
        orders.setUserName(user.getName());                 //下单人

        orderMapper.insert(orders);
        log.info("订单id: {}",orders.getId());

        //2. 构造订单明细列表数据orderDetails，将orderDetails插入到order_detail表中
        //2.1 根据购物车的商品数据，构造订单明细
        List<OrderDetail> orderDetails = new ArrayList<>();
        cartList.forEach(cart -> {
            //2.2 将购物车对象的数据拷贝给订单明细对象
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            //2.3 关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);

        });
        orderDetailMapper.insertBatch(orderDetails);

        //3. 清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        //4.构造vo对象并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        /*// 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));*/

        //业务处理，修改订单状态、来单提醒
        paySuccess(ordersPaymentDTO.getOrderNumber());

        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders order=orderMapper.getById(id);
        BeanUtils.copyProperties(order,orderVO);
        List<OrderDetail> list=orderDetailMapper.getByOrderId();
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 接单
     * @param dto
     */
    @Override
    public void confirm(OrdersConfirmDTO dto) {
        Orders orders = orderMapper.getById(dto.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }


    /**
     * 检验地址是否超出范围
     * @param address
     * @return
     */
    public boolean checkOutOfRange(String address){
        //获取店铺的地址坐标
        //https://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding

        //https://lbsyun.baidu.com/faq/api?title=webapi/direction-api-v2
        HashMap<String, String> map = new HashMap<>();
        map.put("address",shopProperties.getAddress());
        map.put("output","json");
        map.put("ak",shopProperties.getAk());
        String s = HttpClientUtil.doGet(weChatProperties.getLocationUrl(), map);
        JSONObject json = JSONObject.parseObject(s);
        if (!json.get("status").equals(0)){
            throw new OrderBusinessException("地址解析失败");
        }
        JSONObject jsonObject = json.getJSONObject("result").getJSONObject("location");
        Object lng = jsonObject.get("lng");   //经度
        Object lat = jsonObject.get("lat");   //维度
        String o1 = lat + "," + lng;
        log.info("店铺坐标：{}",s);

        map.put("address",address);
        map.put("output","json");
        map.put("ak",shopProperties.getAk());
        s= HttpClientUtil.doGet(weChatProperties.getLocationUrl(), map);
        json = JSONObject.parseObject(s);
        if (!json.get("status").equals(0)){
            throw new OrderBusinessException("地址解析失败");
        }
        jsonObject = json.getJSONObject("result").getJSONObject("location");
        lng = jsonObject.get("lng");   //经度
        lat = jsonObject.get("lat");   //维度
        String o2 = lat + "," + lng;
        log.info("收货坐标：{}",s);
        map.put("origin",o1);
        map.put("destination", o2);
        s = HttpClientUtil.doGet(weChatProperties.getDistanceUrl(), map);
        json = JSON.parseObject(s);
        if (!json.get("status").equals(0)) { //地址解析失败
            throw new OrderBusinessException(MessageConstant.ADDRESS_PARSE_FAILED);
        }
        JSONArray routes = json.getJSONObject("result").getJSONArray("routes");
        Integer distance = (Integer) routes.getJSONObject(0).get("distance");
        System.out.println("distance = " + distance);

        return distance <= shopProperties.getDistance() ;
    }


    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getDetailsById(Integer id) {
        Orders orders = orderMapper.getDetailsById(id);
        OrderVO orderVO = new OrderVO();
        List<OrderDetail> orderDetails =  orderDetailMapper.getDetailsById(id);
        orderVO.setOrderDetailList(orderDetails);
        BeanUtils.copyProperties(orders,orderVO);
        orderDetails.forEach(orderDetail -> {
            orderVO.setOrderDishes(orderDetail.getName()+","+orderDetail.getAmount());
        });
        return orderVO;
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     * @return
     */
    @Override
    public void cancelOrders(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO,orders);
        //设置取消状态
        orders.setStatus(6);
        // 设置取消时间
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }


    /**
     * 再来一单   service
     * @param id
     */
    @Transactional   //涉及多表操作  使用事务
    @Override
    public void repetitionOrderxzs(Long id) {
        //传入的id 应该是原来的订单id

        //  需要获取当前 userId
        Long userId = BaseContext.getCurrentId();


        //  订单再来一单 涉及 订单表
        //直接查找原来的订单 再拷贝到新的 实体类 插入
        Orders orders = orderMapper.getOrderByIdxzs(id);
        //id  checkoutTime 需要设置为null给自增   number   orderTime  得重搞

        // 原来的 获取订单id
        Long oldOrderId = orders.getId();

        //1.1 需要补充属性字段
        orders.setId(null);    //订单号
        orders.setNumber(System.currentTimeMillis()+"");    //订单号
        orders.setStatus(Orders.PENDING_PAYMENT);           //订单状态：1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        orders.setOrderTime(LocalDateTime.now());           //下单时间
        orders.setPayStatus(Orders.UN_PAID);                //支付状态 0未支付 1已支付 2退款

        orders.setCheckoutTime(null);
        orders.setEstimatedDeliveryTime(null);

        orderMapper.insert(orders);
        log.info("订单id: {}",orders.getId());

        // orderMapper.repetitionOrder(id);


        //  涉及 订单明细表
        // orderDetailMapper.repetitionOrder();
        List<OrderDetail> orderDetail = orderDetailMapper.listOrderDetailByOrderIdxzs(oldOrderId);

        for (OrderDetail detail : orderDetail) {
            detail.setId(null);
            detail.setOrderId(orders.getId());

        }
        orderDetailMapper.insertBatch(orderDetail);

        //不需要清空  不需要返回

    }

    /**
     * 历史订单查询  service
     * @param ordersHistoryxzsDTO
     * @return
     */
    @Override
    public PageResult listHistoryOrdersxzs(OrdersHistoryxzsDTO ordersHistoryxzsDTO) {

        //获取 userId
        Long userId = BaseContext.getCurrentId();

        // 使用分页插件
        PageHelper.startPage(ordersHistoryxzsDTO.getPage(),ordersHistoryxzsDTO.getPageSize());

        // 调用mapper层查询数据  订单数据
         Page<OrderHistoryxzsVO> pageVO = orderMapper.listHistoryOrdersxzs(userId,ordersHistoryxzsDTO.getStatus());
        long total = pageVO.getTotal();
        List<OrderHistoryxzsVO> result = pageVO.getResult();
        // 使用 mapper 层查询 订单明细数据

        for (OrderHistoryxzsVO orderHistoryxzsVO : result) {
            // ArrayList<OrderDetail> orderDetails = new ArrayList<>();
            //根据 订单id 找到所有订单下的订单明细
            Long orderId = orderHistoryxzsVO.getId();

            List<OrderDetail> orderDetails1 = orderDetailMapper.listOrderDetailByOrderIdxzs(orderId);
            orderHistoryxzsVO.setOrderDetailList(orderDetails1);

        }

        // 封装数据 并返回

        return new PageResult(total,result);
    }



    /**
     * 统计各个订单的状态
     * @return
     */
    @Override
    public OrderStatisticsVO statusCount() {
        //统计待接单的订单数量
        Integer toBeConfirmed = Orders.TO_BE_CONFIRMED;//待接单
        toBeConfirmed = orderMapper.showStatusCount(toBeConfirmed);//2

        //统计待派送的订单数据
        Integer confirmed = Orders.CONFIRMED;//待派送
        confirmed = orderMapper.showStatusCount(confirmed);//3

        //统计派送中的订单数据
        Integer deliveryInProgress = Orders.DELIVERY_IN_PROGRESS;//派送中
        deliveryInProgress = orderMapper.showStatusCount(deliveryInProgress);//4


        //构建vo数据
        OrderStatisticsVO vo =OrderStatisticsVO
                .builder()
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .toBeConfirmed(toBeConfirmed)
                .build();

        return vo;
    }

    /**
     * 完成订单
     */
    @Override
    public void complete(Integer id) {
        //获取订单
       Orders order= orderMapper.getByIdHsj(id);
       //修改订单状态
       order.setStatus(Orders.COMPLETED);
       //更新订单
       orderMapper.update(order);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //根据id查询订单
        Orders ordersDB = orderMapper.getById();

        //校验订单是否存在，并且状态为3；
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        //更新订单状态，状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);

    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page=orderMapper.pageQuery(ordersPageQueryDTO);

        //
        List<OrderVO> orderVOList=getOrderVoList(page);
        return new PageResult(page.getTotal(),orderVOList);
    }

    private List<OrderVO> getOrderVoList(Page<Orders> page){
        //需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList=new ArrayList<>();
        List<Orders> ordersList=page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)){
            for (Orders orders : ordersList) {
                //将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                String orderDishes=getOrderDishesStr(orders);
                //将订单菜品信息封装到orderVOid中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                ordersList.add(orderVO);
            }
        }
        return orderVOList;
    }
    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 拒绝订单
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO dto) {
        //获取订单id
        Long orderId = dto.getId();
        Orders orders = orderMapper.getByOrderId(orderId);
        //判断订单状态是不是待接单状态
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED){
            //根据订单id拒绝对应的订单
            orders.setStatus(Orders.CANCELLED);
            orders.setRejectionReason(dto.getRejectionReason());
            orderMapper.update(orders);
        }else{
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 取消订单
     * @param dto
     */
    @Override
    public void cancelOrder(OrdersCancelDTO dto) {
        Long orderId = dto.getId();
        Orders orders = orderMapper.getByOrderId(orderId);
        //如果订单状态是2、待接单  3、已接单 6、已取消 中的一种 则抛出异常
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED ||
                orders.getStatus() == Orders.COMPLETED ||
                orders.getStatus() == Orders.CANCELLED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
            //其他情况符合条件，则执行下列程序
        }else {
            //修改状态
            orders.setStatus(Orders.CANCELLED);
            //设置取消原因
            orders.setCancelReason(dto.getCancelReason());
            //更改表单
            orderMapper.update(orders);}
    }
}
